/**
 * 动态监控document大小实现参数传递
 */
seajs.use(['jquery'], function ($) {
    //判断是否嵌套在iframe
    if (window.parent !== window) {
        var getUrlPara = function (name, url) {
            url = url || window.location.href;
            var search = getUrlObj(url).search;
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = search.match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            }
            return "";
        };

        var getUrlObj = function (url) {
            url = url || location.href;

            if (url.indexOf('http') === 0) {
                //nothing
            } else if (url.indexOf('//') === 0) {
                url = location.protocol + url;
            } else if (url.indexOf('/') === 0) {
                url = location.protocol + '//' + location.host + url;
            } else if (url.indexOf('/') !== 0) {
                //相对路径
                url = location.protocol + '//' + location.host + location.pathname.substring(0, location.pathname.lastIndexOf('/')) + '/' + url;
            }

            var l = document.createElement("a");
            l.href = url;

            var pathname = l.pathname;
            if (pathname.indexOf('/') !== 0) {
                pathname = '/' + pathname;
            }

            return {
                protocol: l.protocol,
                host: l.host,
                hostname: l.hostname,
                search: l.search.replace('?', ''),
                hash: l.hash.replace('#', ''),
                pathname: pathname,
                port: l.port
            };
        };

        var getCookie = function (name) {
            var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
            if (arr != null) {
                return unescape(arr[2]);
            }
            return "";
        };

        //从url参数中获取桥接iframe url地址参数
        var bridgeUrl = getUrlPara('bridge_url');
        //如果url参数未取到，从cookie中获取
        if (!bridgeUrl) {
            bridgeUrl = getCookie('bridge_url');
        }

        var $iframe;

        function updateData(data) {
            if (!$iframe) {
                $iframe = $('<iframe style="display:none"/>');
                $iframe.appendTo('body');
            }

            $iframe.attr('src', bridgeUrl + '#?' + $.param(data));
        }

        var heightCache;
        setInterval(function () {
            var height = $(document).height();
            if (heightCache != height) {
                updateData({
                    height: height
                });

                heightCache = height;
            }
        }, 50);
    }
});

